import { GroupChatService } from '../utils/stomp/websocketStomp';
import { provide, inject, type Ref, ref, onUnmounted } from 'vue';

const GROUP_CHAT_SERVICE = Symbol('groupChatService');

export function provideGroupChatService() {
    const service = new GroupChatService();
    const isConnected: Ref<boolean> = ref(false);

    // 连接服务
    service.connect();
    isConnected.value = true;

    // 组件卸载时自动断开连接
    onUnmounted(() => {
        service.disconnect();
        isConnected.value = false;
    });

    provide(GROUP_CHAT_SERVICE, {
        service,
        isConnected
    });
}

export function useGroupChat() {
    const context = inject<{
        service: GroupChatService;
        isConnected: Ref<boolean>;
    }>(GROUP_CHAT_SERVICE);

    if (!context) {
        throw new Error('useGroupChat() called without provider');
    }

    return context;
}